package com.jjyu.service.impl;

import com.jjyu.dao.RecommendationMapper;
import com.jjyu.dao.RestaurantMapper;
import com.jjyu.entity.Restaurant;
import com.jjyu.entity.Recommendation;
import com.jjyu.service.RecommendationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class RecommendationServiceImpl implements RecommendationService {

    @Autowired
    private RestaurantMapper restaurantMapper;

    @Autowired
    private RecommendationMapper recommendationMapper; // 添加推荐记录的Mapper

    @Override
    public Map<String, Object> getRandomRecommendation(int userId) {
        List<Restaurant> restaurants = restaurantMapper.getAllRestaurant();

        if (restaurants.isEmpty()) {
            return createResponse(404, "No restaurants found");
        }

        Restaurant selectedRestaurant = restaurants.get(new Random().nextInt(restaurants.size()));

        // 记录推荐结果
        saveRecommendation(userId, selectedRestaurant.getRestaurantId());

        Map<String, Object> responseData = new HashMap<>();
        responseData.put("restaurant", selectedRestaurant.getName());
        responseData.put("address", selectedRestaurant.getAddress());
        responseData.put("rating", selectedRestaurant.getRating());

        return createResponse(200, "success", responseData);
    }

    private void saveRecommendation(int userId, int restaurantId) {
        Recommendation recommendation = new Recommendation();
        recommendation.setUserId(userId);
        recommendation.setRestaurantId(restaurantId);
        recommendation.setTimestamp(LocalDateTime.now()); // 设置当前时间
        // 这里可以设置 rating，如果需要的话
        recommendation.setRating(0.00);
        recommendationMapper.insertRecommendation(recommendation); // 调用Mapper插入数据
    }

    private Map<String, Object> createResponse(int success, String message, Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", message);
        response.put("data", data);
        return response;
    }

    private Map<String, Object> createResponse(int error, String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("error", error);
        response.put("message", message);
        return response;
    }
}
